package com.bocai.controller;

import com.bocai.bean.CustomEvent;
import com.bocai.bean.TCMObject;
import com.bocai.service.ICompetitionService;
import com.bocai.service.ICountryService;
import com.bocai.service.ICustomEventService;
import com.bocai.utils.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Cemetery on 2018-04-10.
 */
@Controller
@RequestMapping("country")
public class CountryController {

    @Autowired
    private ICountryService countryService;

    @Autowired
    private ICompetitionService competitionService;

    @Autowired
    private ICustomEventService customEventService;

    @ApiOperation(value = "查询国家列表", notes = "获取国家列表")

    @RequestMapping(value = "/getCountryList", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData searchCountry() {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);

        return this.countryService.selectAllCountry(data);
    }


    @ApiOperation(value = "客户端查询赛事列表,不包含被禁用的赛事", notes = "查询赛事列表")

    @RequestMapping(value = "/competitionList", method = RequestMethod.GET)

    @ResponseBody
    public ResponseData competitionList(Integer countryId) {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);
        return this.competitionService.selectAllCompetition(countryId, 0,null,null,data);
    }

    @ApiOperation(value = "服务端查询比赛列表", notes = "查询比赛列表")

    @RequestMapping(value = "/eventList", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "countryId", dataType = "Integer", required = false, value = "国家id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "enabled", dataType = "int", required = false, value = "是否包含被禁用的比赛，不传为包含", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "competitionId", dataType = "Integer", required = false, value = "赛事id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "date", dataType = "string", required = true, value = "比赛开始日期 yyyy-MM-dd", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "endDate", dataType = "string", required = false, value = "比赛开始日期 yyyy-MM-dd 和date是时间段，如果不传只查询date当天", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "keyword", dataType = "string", required = false, value = "筛选关键词,球队名，比赛id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "state", dataType = "int", required = false, value = "状态参考EventState,0未开赛，3进行中,-1被禁止", defaultValue = ""),
    })
    
    @ResponseBody
    public ResponseData eventList(Integer countryId,
                                  Integer competitionId,
                                  String date,
                                  String endDate,
                                  String keyword,
                                  Integer enabled,
                                  Integer state) {
        ResponseData responseData = new ResponseData();
        responseData.setCodeEnum(CodeEnum.SUCCESS);

        CodeEnum codeEnum = ObjUtils.validateParams(new Object[]{date});

        if (ObjUtils.isNotEmpty(codeEnum)) {
            responseData.setCodeEnum(CodeEnum.CODE_90001);
            return responseData;
        }

        Map<String, Object> map = new HashMap<>();
        if (null != countryId) {
            map.put("countryId", countryId);
        }
        if (null != competitionId) {
            map.put("competitionId", competitionId);
        }

        Long beginTime = null;
        Long endTime = null;

        try {

            beginTime = DateUtils.parse(date + " 00:00:00").getTime();

            if (null != endDate) {
                endTime = DateUtils.parse(endDate + " 23:59:59").getTime();
            } else {
                endTime = DateUtils.parse(date + " 23:59:59").getTime();
            }

        } catch (ParseException e) {
            e.printStackTrace();
            responseData.setCodeEnum(CodeEnum.CODE_90002);
            return responseData;
        }

        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("sportId", SysConstant.SPORT_TYPE_FOOTBALL);
        map.put("language", SysConstant.LANGUAGE_TYPE);

        TCMObject object = GetResultUtils.getObject(SysConstant.EVENT_LIST, map);

        JSONArray jsonArray = null;

        try {
         jsonArray = object.getBody().getJSONArray("data");
        }catch (Exception e){
            responseData.setCodeEnum(CodeEnum.CODE_70001);
            return responseData;
        }

        List<JSONObject> temp = new ArrayList<>();

        //被禁用列表,
        CustomEvent cus = new CustomEvent();
        List<CustomEvent> enabledEvents = this.customEventService.selectEvents(cus);

        for (int i = 0; i < jsonArray.size(); i++) {

            JSONObject event = jsonArray.getJSONObject(i);
            event.put("enabled", 0);
            Integer eventId = event.getInt("eventId");

            Boolean isEnabled = false;

            for (CustomEvent enabledEvent : enabledEvents) {
                if (enabledEvent.getEventId().equals(eventId)) {

                    event.put("isHot", enabledEvent.getIsHot());
                    event.put("enabled", enabledEvent.getIsEnable());
                    isEnabled = enabledEvent.getIsEnable() == 1;

                    break;
                }
            }

            if (isEnabled && null != enabled) {
                continue;
            }

            //如果有关键词，处理关键词
            if (null != keyword && keyword.trim().length() > 0) {

                String competitionName = event.getString("competitionName");
                String homeTeam = event.getString("homeTeamName");
                String awayTeam = event.getString("awayTeamName");
                if (!(competitionName.contains(keyword) ||
                        homeTeam.contains(keyword) ||
                        awayTeam.contains(keyword) ||
                        (eventId + "").contains(keyword))) {
                    continue;
                }
            }

            //判断是否需要筛选状态
            if (null != state) {
                if (state == -1){
                    if (event.getInt("enabled") != 1){
                        continue;
                    }
                }else {
                    Integer event_state = event.getInt("state");
                    if (event_state != state) {
                        continue;
                    }
                }
            }

            temp.add(event);
        }


        responseData.setResults(temp);

        return responseData;
    }

}
